//
//  ZCOrderPayVC.m
//  ZCJZ
//
//  Created by sujeking on 2019/2/27.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "ZCOrderPayVC.h"
#import "ZCOrderPayHeadView.h"
#import "ZCOrderCheckLeftAndRightCell.h"
#import "ZCOrderPayTypeCell.h"
#import "ZCOrderCheckSectionHeadView.h"

#import "ZCOrderViewModel.h"
#import "WZGOrderPayHeadView.h"

#import "WZGPayTypeSelectCell.h"
#import "PaymentManager.h"
#import "ZCPaySuccessVC.h"
#import "ZCOrderPayTableFootView.h"
#import "WZGOrderPayWechatAlertVC.h"
#import "SKBaseWebService.h"
#import "SKWebServiceErrorCode.h"
#import "WZGShareOrderPayVC.h"

typedef NS_ENUM(NSUInteger, ZCOrderPayVCRow) {
    ZCOrderPayVCRow_OSn,
    ZCOrderPayVCRow_OTf,
    ZCOrderPayVCRow_OAf,
    ZCOrderPayVCRow_Count
};


@interface ZCOrderPayVC ()<WXApiManagerDelegate,WZGOrderPayWechatAlertVCDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *doneBtn;
@property (nonatomic, copy) NSArray *titles;

@property (nonatomic, copy) NSDictionary *result;

@property (nonatomic, copy) NSDictionary *payType;

@property (assign, nonatomic) BOOL isPaySuccess;

@property (nonatomic, copy) NSString *paypwd;

@property (assign, nonatomic) NSInteger wrong_pwd_count;

@property (assign, nonatomic) NSInteger order_type;
@property (nonatomic, copy) NSString *has_paypwd;

@property (nonatomic, strong) ZCOrderPayTableFootView *tfview;
@property (nonatomic, copy) NSDictionary *lastPayType;

@property (assign, nonatomic) BOOL use_wallet; //1 组合支付
@property (assign, nonatomic) NSInteger lastRow;

@property (assign, nonatomic) BOOL is_group_buy_leader; //是否是开团购买的团长

@end

@implementation ZCOrderPayVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self netFetchOrderPayInfo];
    [PaymentManager sharedManager].delegate = self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.lastPayType != nil) {
        self.payType = self.lastPayType;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [PaymentManager sharedManager].delegate = nil;
    if (self.callback) {
        self.callback(self.isPaySuccess);
    }
}

- (void)setupUI {
    self.navTitle = @"支付订单";
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderCheckLeftAndRightCell" bundle:nil]
         forCellReuseIdentifier:@"ZCOrderCheckLeftAndRightCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderPayTypeCell" bundle:nil]
         forCellReuseIdentifier:@"ZCOrderPayTypeCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WZGPayTypeSelectCell" bundle:nil]
         forCellReuseIdentifier:@"WZGPayTypeSelectCell"];
    
    
    UIView *headerView = [[UIView alloc] initWithFrame:(CGRect){0,0,ScreenWidth,110}];
    UINib *nib = [UINib nibWithNibName:@"ZCOrderPayTableFootView" bundle:nil];
    ZCOrderPayTableFootView *view = [nib instantiateWithOwner:self options:nil].firstObject;
  view.backgroundColor = [generalToolBox getColorWithHexadecimalColorStr:@"0xf3f4f5"];
    view.frame = headerView.bounds;
    [headerView addSubview:view];
    self.tableView.tableFooterView = headerView;
    
    self.doneBtn.backgroundColor = [UIColor redColor];
    [self.doneBtn setTitle:@"确认支付" forState:UIControlStateNormal];
    
    self.tfview = view;
    
    self.use_wallet = NO;
}

// MARK: - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return ZCOrderPayVCRow_Count;
    } else {
        NSArray *type = [self.result valueForKey:@"type"];
        return type.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;
    if (section == 0) {
        ZCOrderCheckLeftAndRightCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderCheckLeftAndRightCell"
                                                                             forIndexPath:indexPath];
        NSArray *tips = self.titles[section];
        cell.keystr = tips[row];
      cell.value_color = [generalToolBox getColorWithHexadecimalColorStr:@"0x999999"];
        switch (row) {
            case ZCOrderPayVCRow_OSn:
            {
                cell.valuestr = [self.dict valueForKey:@"order_sn"];
            }
                break;
            case ZCOrderPayVCRow_OTf: {
                CGFloat v = [[self.dict valueForKey:@"total_fee"] floatValue];
                cell.valuestr = [NSString stringWithFormat:@"￥%.2f",v];
            }
                break;
            case ZCOrderPayVCRow_OAf: {
                CGFloat v = [[self.dict valueForKey:@"actual_fee"] floatValue];
                cell.valuestr = [NSString stringWithFormat:@"￥%.2f",v];
                cell.value_color = [UIColor redColor];
            }
                break;
            default:
                break;
        }
        
        return cell;
    } else {
        WZGPayTypeSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WZGPayTypeSelectCell"
                                                                   forIndexPath:indexPath];
        NSArray *type = [self.result valueForKey:@"type"];
        NSDictionary *dict = type[row];
        cell.dict = dict;
        cell.pt = [[dict valueForKey:@"id"] stringValue];
        NSInteger ids = [[dict valueForKey:@"id"] integerValue];
        if (ids == 1) {
            cell.wallet = [[self.result valueForKey:@"detail"] valueForKey:@"wallet"];
        }
        cell.message = [dict valueForKey:@"message"];
        return cell;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
//        UINib *nib = [UINib nibWithNibName:@"ZCOrderPayHeadView" bundle:nil];
        UINib *nib = [UINib nibWithNibName:@"WZGOrderPayHeadView" bundle:nil];
        WZGOrderPayHeadView *view = [nib instantiateWithOwner:self options:nil].firstObject;
//        ZCOrderPayHeadView *view = [nib instantiateWithOwner:self options:nil].firstObject;
        NSDictionary *detail = [self.result valueForKey:@"detail"];
        view.dict = detail;
        return view;
    } else {
        UINib *nib = [UINib nibWithNibName:@"ZCOrderCheckSectionHeadView" bundle:nil];
        ZCOrderCheckSectionHeadView *view = [nib instantiateWithOwner:self options:nil].firstObject;
        view.title = @"支付方式";
      view.backgroundColor = [generalToolBox getColorWithHexadecimalColorStr:@"0xf4f5f6"];
        return view;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 70;
    } else {
        return 30.0f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 00.0001f;
    } else {
        return 0.001f;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    if (section == 1) {
        NSArray *type = [self.result valueForKey:@"type"];
        NSDictionary *dict = type[row];
        BOOL enable = [[dict valueForKey:@"enable"] boolValue];
        NSInteger _id = [[dict valueForKey:@"id"] integerValue];
        self.use_wallet = NO;
        if (enable) {
            if (_id == 1) {
                self.use_wallet = YES;
            }
            self.lastRow = row;
            self.payType = dict;
            self.lastPayType = dict;
        } else {
            NSIndexPath *path = [NSIndexPath indexPathForRow:self.lastRow inSection:1];
            [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
        }
    }
}

- (void)selectPayType {
    NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:1];
    NSArray *type = [self.result valueForKey:@"type"];
    self.payType = type.firstObject;
    self.lastPayType = type.firstObject;
    self.lastRow = 0;
    [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
}

- (IBAction)payBtnClickAction:(id)sender {
    NSInteger ids = [[self.payType valueForKey:@"id"] integerValue];
    __weak typeof(self) weakSelf = self;
    if (ids == 1) {
        CGFloat actual_fee = [[self.dict valueForKey:@"actual_fee"] floatValue];
        CGFloat wallet = self.userModel.member.wallet.floatValue;
        
        NSDictionary *detail = [self.result valueForKey:@"detail"];
        NSString *order_sn = [detail valueForKey:@"order_sn"];
        NSString *pay_type = [self.payType valueForKey:@"id"];

        if (wallet >= actual_fee) {
            [self netPayInfo2ServerWithInfo:@[order_sn,pay_type]];
        } else {
            NSMutableArray *marr = [NSMutableArray new];
            NSArray *arr = [[self.result valueForKey:@"type"] mutableCopy];
            for (NSDictionary *dict in arr) {
                if ([[dict valueForKey:@"id"] intValue] == 2 ||[[dict valueForKey:@"id"] intValue] == 3) {
                    [marr addObject:dict];
                }
            }
            WZGOrderPayWechatAlertVC *vc = [[WZGOrderPayWechatAlertVC alloc] init];
            [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
            vc.goodsprice = [self.dict valueForKey:@"actual_fee"];
            vc.payType = marr.copy;
            vc.delegate = self;
            
            [vc setDismissCallback:^(NSInteger flag) {
                if (flag == 0) {
                    weakSelf.use_wallet = 1;
                    NSArray *type = [self.result valueForKey:@"type"];
                    weakSelf.payType = type[1];
                    [weakSelf netPayInfo2ServerWithInfo:@[order_sn,[weakSelf.payType valueForKey:@"id"]]];
                }
                if (flag == 1) {
//                    WZGReChargeVC *vc = [[WZGReChargeVC alloc] init];
//                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
            }];
            [self.view.window.rootViewController presentViewController:vc animated:YES completion:nil];
        }
    }
    if (ids == 2) {
        NSDictionary *detail = [self.result valueForKey:@"detail"];
        NSString *order_sn = [detail valueForKey:@"order_sn"];
        NSString *pay_type = [self.payType valueForKey:@"id"];
        [self netPayInfo2ServerWithInfo:@[order_sn,pay_type]];
    }
    
    if (ids == 3) {
        NSDictionary *detail = [self.result valueForKey:@"detail"];
        NSString *order_sn = [detail valueForKey:@"order_sn"];
        NSString *pay_type = [self.payType valueForKey:@"id"];
        [self netPayInfo2ServerWithInfo:@[order_sn,pay_type]];
    }
    if (ids == 11) {
        WZGShareOrderPayVC *vc = [[WZGShareOrderPayVC alloc] init];
        vc.dict = [self.result valueForKey:@"detail"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)loadAliPayWithInfo:(NSDictionary *)dict {
    __weak typeof(self) weakSelf = self;
    [[PaymentManager sharedManager] loginAliPayWithOrderSignStr:[dict valueForKey:@"requestUrl"] callback:^(NSDictionary *dict) {
        NSInteger resultStatus = [[dict valueForKey:@"resultStatus"] integerValue];
        if (resultStatus == 6001) {
            [weakSelf.view makeToast:@"您取消了支付" duration:2.0 position:CSToastPositionCenter];
            if (self.lastPayType != nil) {
                self.payType = self.lastPayType;
            }
            return;
        } else if (resultStatus == 9000) {
            weakSelf.isPaySuccess = YES;
            [weakSelf netGetInvidateCode];
            return;
        } else {
            [weakSelf.view makeToast:@"支付失败,请重试" duration:2.0 position:CSToastPositionCenter];
            if (self.lastPayType != nil) {
                self.payType = self.lastPayType;
            }
        }
    }];
}

- (void)loadWX2payWithInfo:(NSDictionary *)dict {
    if (![WXApi isWXAppInstalled]) {
        return;
    }
    [PaymentManager sharedManager].delegate = self;
    [[PaymentManager sharedManager] loadWXPayWithWithOrderSignInfo:dict];
}


- (void)loadWXMiniProgram2pay {
    if (![WXApi isWXAppInstalled]) {
        return;
    }
    NSString *order_id = [self.dict valueForKey:@"order_id"];
    [PaymentManager sharedManager].delegate = self;
    [[PaymentManager sharedManager] loadWeiXinMiniProgram:order_id];
}

// MARK: - WXApiManagerDelegate

- (void)managerDidRecvPaymentResponse:(PayResp *)response {
    if (response.errCode == 0) {
        self.isPaySuccess = YES;
        [self netGetInvidateCode];
        return;
    } else if (response.errCode == -2) {
        [self.view makeToast:@"您取消了支付" duration:2.0 position:CSToastPositionCenter];
        if (self.lastPayType != nil) {
            self.payType = self.lastPayType;
        }
        return;
    } else {
        [self.view makeToast:@"支付失败,请重试" duration:2.0 position:CSToastPositionCenter];
        if (self.lastPayType != nil) {
            self.payType = self.lastPayType;
        }
    }
}

// MARK: - WZGOrderPayWechatAlertVCDelegate

- (void)WZGOrderPayWechatAlertVCWithdraw {
//    WZGReChargeVC *vc = [[WZGReChargeVC alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
}

- (void)WZGOrderPayWechatAlertVCPayWithPayType:(NSInteger)payType {
    self.use_wallet = 1;
    NSArray *type = [self.result valueForKey:@"type"];
    for (NSDictionary *dict in type) {
        if ([[dict valueForKey:@"id"] intValue] == payType) {
            self.payType = dict;
            break;
        }
    }
    NSDictionary *detail = [self.result valueForKey:@"detail"];
    NSString *order_sn = [detail valueForKey:@"order_sn"];
    [self netPayInfo2ServerWithInfo:@[order_sn,@(payType)]];
}

// MARK: - NET

- (void)netCheckMemberHasPasswd {
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [SKBaseWebService getRequest:@"/v1/pay/check-member" parameters:parameters progress:nil success:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        weakSelf.has_paypwd = [[data valueForKey:@"has_paypwd"] stringValue];
        weakSelf.userModel.member.has_paypwd = weakSelf.has_paypwd;
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        });
    } failure:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        [weakSelf.view makeToast:@"网络错误" duration:2.0 position:CSToastPositionCenter];
    }];
}

- (void)netFetchOrderPayInfo {
    if (self.order_id == nil) {
        self.order_id = [self.dict valueForKey:@"order_id"];
    }
    if (self.order_id == nil) {
        [self.view makeToast:@"网络错误" duration:2.0 position:CSToastPositionCenter];
        return;
    }
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCOrderViewModel fetchOrderPayInfoWithOrderId:self.order_id complete:^(ZCErrorCode status, NSString *message, id data) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (status == kHXSNoError) {
            weakSelf.order_type = [[[data valueForKey:@"detail"] valueForKey:@"type"] integerValue];
                  weakSelf.groupSN = [[data valueForKey:@"detail"] valueForKey:@"group_sn"];
                  weakSelf.is_group_buy_leader = [[[data valueForKey:@"detail"] valueForKey:@"is_lead"] boolValue];
                  weakSelf.tfview.timestr = [[[data valueForKey:@"detail"] valueForKey:@"overtime"] stringValue];
                  weakSelf.userModel.member.wallet = [[data valueForKey:@"detail"] valueForKey:@"wallet"];
                  
                  weakSelf.result = data;
                  [weakSelf.tableView reloadData];
                  [weakSelf selectPayType];
        } else if (status == kHXSInvalidTokenError) {
//            WZGLoginVC *vc = [[WZGLoginVC alloc] init];
//            [vc setGoodsVCCallBack:^(NSInteger type) {
//                [weakSelf netFetchOrderPayInfo];
//            }];
//            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
//            [weakSelf.navigationController presentViewController:nvc animated:YES completion:nil];
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

- (void)netPayInfo2ServerWithInfo:(NSArray *)info {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCOrderViewModel postOrderPayInfoWithOrderSN:info.firstObject
                                          payType:info.lastObject
                                           paypwd:self.paypwd
                                        useWallet:@(self.use_wallet).stringValue complete:^(ZCErrorCode status, NSString *message, id data) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (status == kHXSNoError) {
            NSInteger pt = [[weakSelf.payType valueForKey:@"id"] integerValue];
            if (pt == 1) {
                weakSelf.isPaySuccess = YES;
                [weakSelf netGetInvidateCode];
            }
            if (pt == 2) {
                [weakSelf loadAliPayWithInfo:data];
            }
            if(pt == 3) {
                [weakSelf loadWX2payWithInfo:data];
            }
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
            if (status == kHXSPaypassError) {
                if (weakSelf.wrong_pwd_count >= 2) {
                  
                  
                } else {
                    ++weakSelf.wrong_pwd_count;
                }
            }
        }
    }];
}

- (void)netGetInvidateCode {
    __block NSString *order_id = [self.dict valueForKey:@"order_id"];
    if (self.order_type != 16) { //16为礼包
        if (self.order_type == 3) { //拼团
            if (self.is_group_buy_leader) {
//                WZGGroupBuyOpenStatusVC *vc = [[WZGGroupBuyOpenStatusVC alloc] init];
//                vc.group_sn = self.groupSN;
//                NSMutableArray *vcs = [[self.navigationController childViewControllers] mutableCopy];
//                [vcs removeObject:self];
//                [vcs addObject:vc];
//                [self.navigationController setViewControllers:vcs animated:YES];
            } else {
//                WZGGroupBuyJoinStatusVC *vc = [[WZGGroupBuyJoinStatusVC alloc] init];
//                vc.group_sn = self.groupSN;
//                NSMutableArray *vcs = [[self.navigationController childViewControllers] mutableCopy];
//                [vcs removeObject:self];
//                [vcs addObject:vc];
//                [self.navigationController setViewControllers:vcs animated:YES];
            }
            return;
        }
        //常规
        ZCPaySuccessVC *vc = [[ZCPaySuccessVC alloc] init];
        vc.orderId = order_id;
        vc.is_order_list = self.isOrderList;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:order_id forKey:@"id"];
    [SKBaseWebService getRequest:@"/v1/order/gift-code" parameters:parameters progress:nil success:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        NSString *gift_code = [data valueForKey:@"gift_code"];
        ZCPaySuccessVC *vc = [[ZCPaySuccessVC alloc] init];
        vc.orderId = order_id;
        vc.is_order_list = weakSelf.isOrderList;
        vc.gift_code = gift_code;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    } failure:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        NSLog(@"%s:%@",__FUNCTION__,msg);
    }];

}

// MARK: - GET

- (NSArray *)titles {
    if (_titles == nil) {
        _titles = @[@[@"订单号",@"订单金额",@"实付金额"],@[@"余额支付"]];
    }
    return _titles;
}

@end
